package com.base.vistter.iframe.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.base.vistter.iframe.constant.UserConstant;
import com.base.vistter.iframe.model.LoginUserModel;
import com.base.vistter.iframe.properties.IframeProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
@Slf4j
@Component
public class JwtUtils {

    private static IframeProperties iframeProperties;
    /**
     * 创建token
     * @param secret 加密秘钥
     * @return
     * @throws IllegalArgumentException
     */
    public static String createToken(LoginUserModel loginUserModel, String secret) throws IllegalArgumentException {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE , iframeProperties.getTimeout());
        JWTCreator.Builder builder = JWT.create()
                .withClaim(UserConstant.USER_ID, loginUserModel.getUserId())
                .withClaim(UserConstant.USERNAME, loginUserModel.getUsername())
                .withClaim(UserConstant.DEPART_ID, loginUserModel.getDepartId())
                .withClaim(UserConstant.FIRM_ID , loginUserModel.getFirmId())
                .withClaim(UserConstant.ROLE_ID, loginUserModel.getRoleId())
                .withClaim(UserConstant.IS_ADMIN, loginUserModel.getIsAdmin())
                .withExpiresAt(calendar.getTime());
        return builder.sign(Algorithm.HMAC256(secret));
    }

    private static DecodedJWT getDecodedJWT(String token){
        return JWT.decode(token);
    }

    /**
     * 过期时间
     * @param token
     * @return
     */
    public static Date getExpiresDate(String token){
        return getDecodedJWT(token).getClaim("exp").asDate();
    }

    /**
     * 验证token是否有效
     * @param token 登录凭证
     * @param secret 秘钥
     * @return
     */
    public static DecodedJWT verifyToken(String token , String secret) throws TokenExpiredException {
        return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
    }

    public static int claimToInt(DecodedJWT decodedJWT ,String key){
        Claim claim = decodedJWT.getClaim(key);
        if(claim != null){
            return claim.asInt();
        }
        return 0;
    }

    public static String claimToString(DecodedJWT decodedJWT ,String key){
        Claim claim = decodedJWT.getClaim(key);
        if(claim != null){
            return claim.asString();
        }
        return "";
    }

    @Resource(name = "iframeProperties")
    public void setIframeProperties(IframeProperties iframeProperties){
        JwtUtils.iframeProperties = iframeProperties;
    }
}
